//-----------------------------------------------------------------------------
//
// FifteenPuzzle
//
// Eugene Magdel and Joshua Jung
//
// 2011 for University of Illinois at Chicago CS340 w/ Professor Troy
//
//-----------------------------------------------------------------------------
#include "block.h"
#include "grid.h"
#include "stdlib.h"
#include "sstream"

//-----------------------------------------------------------------------------
//
// Constructor
//
//-----------------------------------------------------------------------------
Block::Block(int val, bool emp, Grid *_board) : value(val), empty(emp){
  board = _board; 
  prev = NULL;
  next = NULL;

  std::stringstream ss;

  ss << "../images/Tile" << value << ".jpg";

  pm = new QPixmap(ss.str().c_str());
}

//-----------------------------------------------------------------------------
//
// Methods
//
//-----------------------------------------------------------------------------
/**
 * Moves this block by telling the board to move it.
 */
void Block::move(){
  board -> move(this);
}

/**
 * Returns true if this is the "empty" block. The empty block is actually the 16th "missing" block needed to
 * complete the puzzle.
 */
bool Block::is_empty(){
    return empty;
}

/**
 * Returns the value (position) of the block from 0-15.
 */
int Block::get_value(){
  return value;
}

/**
 * Returns true if this block is supposed to be in a position greater than the provided block.
 *
 * Used to figure out of the board is solvable when counting inversions.
 */
bool Block::operator>(Block *other){
  return get_value() > other -> get_value();
}

/**
  * Draw the block by positioning it in its parent graphic view.
  *
  * If the block is the empty block then don't display it unless the puzzle
  * is solved.
  */
void Block::draw_tile(bool isSolved){
    if (!is_empty() || isSolved)
    {
        Block * cur = this;

        // Calculate the current position of this block in
        // the list, which we use to determine the x and y coordinate.
        int i=0;

        while(cur -> prev != NULL){
            cur = cur -> prev;
            ++i;
        }

        pmi->setX((i % (board -> rows())) * 48 + ((i % (board -> rows()) - 1)) * 2);
        pmi->setY((i / (board -> rows())) * 48 + ((i / (board -> rows()) - 1)) * 2);
    }
    else
    {
        pmi->setX(-10000);
        pmi->setY(-10000);
    }
}

/**
 * This initializes the tiles graphic
 */
void Block::initialize_tile(QGraphicsScene *graphicsScene){
    pmi = graphicsScene->addPixmap(*pm);
    pmi->setScale(0.5);
}
